package com.fufan.mtsaas.modules.sysmgr.sylogtemp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.sylogtemp.service.SyinplogSvc;
import com.github.pagehelper.ISelect;
import com.fufan.mtsaas.modules.sysmgr.sylogtemp.dao.SyinplogDao;
import com.fufan.mtsaas.modules.sysmgr.sylogtemp.model.Syinplog;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.sylogtemp.service.SyinplogSvc;
import com.fufan.mtsaas.util.JSonUtil;
import com.fufan.mtsaas.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Liby
 * @since 2019-09-11
 */
@Service("SyinplogSvcImpl")
@Slf4j
@Primary
public class SyinplogSvcImpl extends ServiceImpl<SyinplogDao, Syinplog> implements SyinplogSvc {
    @Autowired
    private SyinplogDao entitymDao;

    @Value("${COMPANY_CD}")
    private String COMPANY_CD;

    /**
     * 查询
     *
     * @param map
     * @return Result.class
     * */
    @Override
    public Result doQueryPage(Map<String, String> map) {
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SyinplogSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();
        String CompanyID = null;
        String UserID = null;
        String ErrorMsg = null;
        try {
            CompanyID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("CompanyID").toString();
        }catch (Exception e){
            log.debug("SyinplogSvcImpl.doQueryPage get CompanyID parameter is not found.");
        }
        try {
            UserID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("UserID").toString();
        }catch (Exception e){
            log.debug("SyinplogSvcImpl.doQueryPage get UserID parameter is not found.");
        }
        try {
            ErrorMsg = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("ErrorMsg").toString();
        }catch (Exception e){
            log.debug("SyinplogSvcImpl.doQueryPage get ErrorMsg parameter is not found.");
        }
        String ExpID = null;
        try {
            ExpID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("ExpID").toString();
        }catch (Exception e){
            log.debug("SyinplogSvcImpl.doQueryPage get ExpID parameter is not found.");
        }

        //赋值默认
        if(StringUtils.isEmpty(CompanyID)){
            CompanyID = COMPANY_CD;
        }
        mapData.put("CompanyID", CompanyID);
        mapData.put("UserID", UserID);
        mapData.put("ExpID", ExpID);
        mapData.put("ErrorMsg", ErrorMsg);

        List<Syinplog> entitys;

        ParamUtil.setPage(map, page);
        //分页处理 -- 20192021 Liby
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectList(page, mapData);
            }
        });
        String pageSize = ParamUtil.getParamfromMap(map,"pageSize");
        String currentPage = ParamUtil.getParamfromMap(map,"currentPage");
        if (null != pageSize && null != currentPage) {
            com.github.pagehelper.PageHelper.startPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
        }
        entitys = entitymDao.selectList(page, mapData);

        log.debug("SyinplogSvcImpl.doQueryPage entitys: {}", entitys);

        page.setTotal((int) total);
        page.setRecords(entitys);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 新增
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doSave(Syinplog entitym, RequestPojo requestPojo) {
        log.debug("SyinplogSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(StringUtils.isEmpty(entitym.getCompanyID())
                || StringUtils.isEmpty(entitym.getUserID())
                || StringUtils.isEmpty(entitym.getExpID())){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        //名称重复验证
        HashMap mapData = new HashMap();
        Page page = new Page();
        mapData.put("CompanyID", entitym.getCompanyID());
        mapData.put("UserID", entitym.getUserID());
        mapData.put("ExpID", entitym.getExpID());
        List<Syinplog> entity = entitymDao.selectList(page, mapData);
        if(entity != null && entity.size() > 0){
            result.setResStatus(ResStatus.STATUS_EXISTENCE);
            result.setResMsg(ResStatus.STATUS_EXISTENCE_MSG);
            return result;
        }

        try{
            int rec = entitymDao.insertRecords(entitym);
            log.debug("新增数据返回 {}",rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

            result.setResData(page.setRecords(Arrays.asList(entitym)));
        }catch (Exception e){
            log.error("新增数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 修改
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doUpdate(Syinplog entitym, RequestPojo requestPojo) {
        log.debug("SyinplogSvcImpl.doUpdate parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(StringUtils.isEmpty(entitym.getCompanyID())
                || StringUtils.isEmpty(entitym.getUserID())
                || StringUtils.isEmpty(entitym.getExpID())){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }
        try{
            int rec = entitymDao.updateRecords(entitym);
            log.debug("更新数据返回 {}",rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            log.error("修改数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("修改数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 删除
     *
     * @param map
     * @return Result.class
     * */
    @Override
    // @Transactional
    public Result doDelete(Map<String, String> map,RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SyinplogSvcImpl.doDelete parameter: {}", map);
        //非空验证
        String CompanyID = "";
        String UserID = "";

        try {
            CompanyID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("CompanyID").toString();
        }catch (Exception e){
            log.debug("SyinplogSvcImpl.doDelete get CompanyID parameter is not found.");
        }
        try {
            UserID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("UserID").toString();
        }catch (Exception e){
            log.debug("SyinplogSvcImpl.doDelete get UserID parameter is not found.");
        }
        String ExpID = null;
        try {
            ExpID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("ExpID").toString();
        }catch (Exception e){
            log.debug("SyinperrormsgSvcImpl.doQueryPage get ExpID parameter is not found.");
        }

        if(StringUtils.isEmpty(CompanyID)
                || StringUtils.isEmpty(UserID)
                || StringUtils.isEmpty(ExpID)){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        mapData.put("CompanyID", CompanyID);
        mapData.put("UserID", UserID);
        mapData.put("ExpID", ExpID);
        List<Syinplog> entitym = entitymDao.selectList(page, mapData);
        if(entitym == null || entitym.size() == 0){
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg("数据不存在");
            return result;
        }

        try{
            int rec = entitymDao.deleteByPk(mapData);
            log.debug("删除数据返回 {}",rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            log.error("删除数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("删除出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }

        return result;

    }

    @Override
    public Result doSaveMap(String map, RequestPojo requestPojo) {
        log.info("doSaveMap {}", map);
        JSONObject json = JSON.parseObject(map);
        JSONObject data = json.getJSONObject("data");
        Syinplog entitym = JSonUtil.toBean(data.getJSONObject("param").toJSONString(), Syinplog.class);
        requestPojo.setStaffId(ParamUtil.getMetadatafromObject(map, "user"));

        return this.doSave(entitym, requestPojo);
    }

    @Override
    public Result doUpdateMap(String map, RequestPojo requestPojo) {
        log.info("doUpdateMap {}", map);
        JSONObject json = JSON.parseObject(map);
        JSONObject data = json.getJSONObject("data");
        Syinplog entitym = JSonUtil.toBean(data.getJSONObject("param").toJSONString(), Syinplog.class);
        requestPojo.setStaffId(ParamUtil.getMetadatafromObject(map, "user"));

        return this.doUpdate(entitym, requestPojo);
    }
}
